<?php

class RandomUtil {

    /**
     * 按比例随机
     * @param array $array      需要随机的一维数组 如：[0,1,2,3,4,5]
     * @param array $rates      比例配置数组 如：[0=>0,1=>0,2=>0,3=>0.33,4=>0.33,5=>0.34]
     * @return type
     */
    public static function rate($array, $rates) {
        $sum = 0;
        $left = 0;
        $right = 0;
        foreach ($rates as $key => $value) {
            $sum += $value * 100;
        }
        $temp = rand(0, $sum - 1);
        foreach ($rates as $key => $value) {
            $right += $value * 100;
            if ($left <= $temp && $temp < $right) {
                return $array[$key];
            }
            $left += $value * 100;
        }
    }

}

$array = [1, 2, 3, 4, 5];
$rates = [
    1 => 0.33,
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0
];
$nums = [];
for ($i = 0; $i < 10000; $i++) {
    $key = RandomUtil::rate($array, $rates);
    !isset($nums[$key - 1]) && $nums[$key - 1] = 0;
    isset($nums[$key - 1]) && $nums[$key - 1] ++;
}
foreach ($nums as $num) {
    echo $num . "\n";
}
